package security;

import play.mvc.Controller;
import model.forview.LoginModelForView;
import model.wrap.user.User;

/**
 * 
 * @author pocteg
 * 
 */
public class Security
{

    /**
     *********** ATTRIBUTS******************************************************
     * 
     * -------------------INSTANCE---------------------------------------------
     * 
     * -----------------------------PUBLIC-------------------------------------
     */

    /**
     * -----------------------------PROTECTED----------------------------------
     */

    /**
     * -----------------------------PRIVATE------------------------------------
     */

    /**
     ********************* STATIC**********************************************
     * 
     * -----------------------------PUBLIC------------------------------------
     */

    /**
     * Имя сессии для cookie.
     */
    public static final String sessionKey = "intabase_session_key";

    /**
     * -----------------------------PROTECTED---------------------------------
     */

    /**
     * -----------------------------PRIVATE-----------------------------------
     */

    private static final String separatorForSessionKey = "&";

    /**
     *********** CONSTRUCTOR***************************************************
     */

    /**
     *********** METHODS*******************************************************
     * 
     * -------------------INSTANCE--------------------------------------------
     * 
     * -----------------------------PUBLIC------------------------------------
     */

    /**
     * -----------------------------PROTECTED---------------------------------
     */

    /**
     * -----------------------------PRIVATE-----------------------------------
     */

    /**
     ********************* STATIC**********************************************
     * 
     * -----------------------------PUBLIC------------------------------------
     */

    /**
     * @author pocteg
     * @param form
     * @return
     * @throws SecurityException
     */
    public static User authorization(LoginModelForView form) throws SecurityException
    {
	try
	{
	    User user = User.getUser(form.email);
	    if (!form.password.equals(user.getPassword())) throw new SecurityException();
	    setSessionKey(user);
	    return user;
	}
	catch (Exception e)
	{
	    // TODO добавить exception вместо null
	    throw new SecurityException();
	}
    }

    /**
     * Проверяет по сессии, залогинен ли пользователь в системе.
     * 
     * @author pocteg
     * @return
     * @throws SecurityException
     */
    public static boolean isAuthorize() throws SecurityException
    {
	try
	{
	    String sessionKey = Controller.session(Security.sessionKey);
	    User user = getUserFromSession();
	    if (sessionKey.equals(generateSessionKey(user))) return true;
	}
	catch (Exception e)
	{
	    throw new SecurityException();
	}
	throw new SecurityException();
	// return false;
    }

    public static String getUserNameFromSession()
    {
	try
	{
	    String sessionKey = Controller.session(Security.sessionKey);
	    String userName = sessionKey.split(separatorForSessionKey)[0];
	    return userName;
	}
	catch (Exception e)
	{
	    return null;
	}
    }
    
    /**
     * Get user from session
     * 
     * @author pocteg
     * @return Null if have exception
     */
    public static User getUserFromSession()
    {
	try
	{
	    String sessionKey = Controller.session(Security.sessionKey);
	    String userName = sessionKey.split(separatorForSessionKey)[0];
	    return new User(userName);
	}
	catch (Exception e)
	{
	    return null;
	}
    }

    /**
     * @author pocteg
     */
    public static void logoff()
    {
	try
	{
	    Controller.session(Security.sessionKey, "");
	}
	catch (Exception e)
	{
	}
    }

    /**
     * -----------------------------PROTECTED---------------------------------
     */

    /**
     * -----------------------------PRIVATE-----------------------------------
     */

    /**
     * Генерирует ключ сессии для пользователя
     * 
     * @author pocteg
     * @param user
     *            Пользователь, для которого нужно сгенерировать ключ.
     * @return
     */
    private static String generateSessionKey(User user)
    {
	// TODO хешировать ключ сессии.
	return user.getEmail() + separatorForSessionKey + user.getPassword();
    }

    /**
     * Установить сессионый ключ для пользователя. Записывает
     * 
     * @author pocteg
     * @param user
     * @return
     */
    private static String setSessionKey(User user)
    {
	Controller.session(Security.sessionKey, Security.generateSessionKey(user));
	return sessionKey;
    }

    /**
     ****** GETTERS************************************************************
     */

    /**
     ****** SETTERS************************************************************
     */

}
